// src/hooks/createProviderState.ts
import { useState, useEffect, useRef } from 'react';

type SetState<T> = (state: Partial<T> | ((state: T) => Partial<T>)) => void;
type GetState<T> = () => T;

export function createProviderState<T extends object>(
  createState: (set: SetState<T>, get: GetState<T>) => T
) {
  let state: T;
  const subscribers = new Set<() => void>();

  const setState: SetState<T> = (partial) => {
    const newState = typeof partial === 'function' 
      ? partial(state) 
      : partial;
    
    state = { ...state, ...newState };
    subscribers.forEach((listener) => listener());
  };

  const getState: GetState<T> = () => state;

  const subscribe = (listener: () => void) => {
    subscribers.add(listener);
    return () => subscribers.delete(listener);
  };

  const destroy = () => {
    state = undefined!;
    subscribers.clear();
  };

  function useProviderState(): T;
  function useProviderState<U>(selector: (state: T) => U): U;
  function useProviderState<U>(selector?: (state: T) => U): T | U {
    const selectorRef = useRef(selector || ((state: T) => state));
    const [selected, setSelected] = useState(() => selectorRef.current(state));

    useEffect(() => {
      const listener = () => {
        const newSelected = selectorRef.current(state);
        setSelected(prev => {
          // 浅比较避免不必要的渲染
          return JSON.stringify(prev) === JSON.stringify(newSelected) 
            ? prev 
            : newSelected;
        });
      };
      return ()=>{subscribe(listener)};
    }, []);

    return selected;
  }

  // 初始化状态
  state = createState(setState, getState);

  // 附加方法
  Object.assign(useProviderState, {
    getState,
    setState,
    subscribe,
    destroy
  });

  return useProviderState;
}